import React, { PureComponent } from 'react';
import _ from 'lodash';
import { message } from 'antd';
import { ContentPackage, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, ModalC, FormGroup } from '../../../comps';
import UpdateModelC from './updateModelC';
import moment from 'moment';

import { connect, routerRedux } from 'dva';

@connect(({ OutsourceInvestMsgMaintainM, loading, globalM }) => ({ OutsourceInvestMsgMaintainM, loading, globalM }))
export default class OutsourceInvestMsgMaintain extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      searchObj: {},
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      operatePageVisible: false, // 新增或编辑页的显示隐藏
      operateType: 1, //操作类型,  1) 新增, 2) 编辑, 3) 详情, 4) 估值解析
      operateId: undefined, // 操作的id
      deferDateVisible: false, //展期模态框的显示隐藏
      deferDateData: undefined, //展期的数据回填
    };
  }
  componentDidMount() {
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    // 字典接口
    this.props.dispatch({
      type: 'OutsourceInvestMsgMaintainM/getDictionList',
      // [资产类别，  资金实际投向， 委外投资属性,  资金运用行业]
      payload: {
        dictData: dataDictionary,
      },
    });
    // 资金运用行业
    this.props
      .dispatch({
        type: 'OutsourceInvestMsgMaintainM/getFundDictionList',
        // [资金运用行业]
        payload: {
          datakey: 'GJTJJHYFLI',
        },
      })
      .then(() => {
        this.getTableData();
      });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 获取表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage } = this.state;
    this.setState(
      {
        columns: undefined,
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'OutsourceInvestMsgMaintainM/getTableData',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
          },
          callback: (type, data) => {
            if (type == 'success') {
              this.setState({
                columns: data.columns,
                dataSource: data.dataSource,
                total: data.pageInfo && data.pageInfo.total,
              });
            }
          },
        });
      },
    );
  };
  //查询
  queryTableList = (e) => {
    let tempQuery = {};
    for (let k in e) {
      if (k == 'investPlanSetupDateStart' || k == 'investPlanSetupDateEnd' || k == 'investPlanTerminateDateStart' || k == 'investPlanTerminateDateEnd') {
        tempQuery[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempQuery[k] = e[k];
      }
    }
    this.setState(
      {
        searchObj: tempQuery,
        isReset: false,
        currentPage: 1,
        numInPage: 10,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 新增
  addClick = () => {
    this.setState({
      operatePageVisible: true,
      operateType: 1,
    });
  };
  // 展期
  deferDate = (record) => {
    this.setState({
      deferDateVisible: true,
      deferDateData: record,
    });
  };
  // 详情
  itemDetail = (record) => {
    this.setState({
      operatePageVisible: true,
      operateId: record.id,
      operateType: 3,
    });
  };
  // 估值解析
  valuateItem = (record) => {
    sessionStorage.setItem(
      'GZJX_pageJump',
      JSON.stringify({
        dimension: '2',
        assetType: '02',
        code: record.tradingCode,
      }),
    );
    this.props.dispatch(routerRedux.push('/SystemManagement/valuationAnalysis'));
    // this.setState({
    //     operatePageVisible: true,
    //     operateId: record.id,
    //     operateType: 4,
    // })
  };
  // 编辑事件
  editItem = (record) => {
    this.setState({
      operatePageVisible: true,
      operateId: record.id,
      operateType: 2,
    });
  };
  // 删除事件
  deleteItem = (record) => {
    this.props.dispatch({
      type: 'OutsourceInvestMsgMaintainM/deleteById',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        if (res == 'success') {
          this.getTableData();
        }
      },
    });
  };
  // 新增编辑页返回主页
  onBack = (msg, type) => {
    this.setState({
      operatePageVisible: msg,
    });
    if (type == 'ok') {
      this.getTableData();
    }
  };
  // 展期模态框确定事件
  deferDateOk = () => {
    this.deferDateInfoRef.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (moment(fieldsValue.investPlanTerminateDate).format('YYYY-MM-DD') == moment(this.state.deferDateData.investPlanTerminateDate).format('YYYY-MM-DD')) {
        message.warning('还未重新选择终止日期，请重新选择!');
        return;
      }
      this.props.dispatch({
        type: 'OutsourceInvestMsgMaintainM/deferDate',
        payload: {
          tradeId: this.state.deferDateData.id,
          exhibitionPeriod: fieldsValue.investPlanTerminateDate?.format('YYYY-MM-DD'),
        },
        callback: (type) => {
          if (type == 'success') {
            this.getTableData();
          }
        },
      });
      this.setState({
        deferDateVisible: false,
      });
    });
  };
  // 展期模态框取消事件
  deferDateCancel = () => {
    this.setState({
      deferDateVisible: false,
    });
  };
  // 展期页面渲染
  deferDateInfo = () => {
    return (
      <>
        <FormGroup
          dataSource={[
            {
              dataIndex: 'investPlanSetupDate',
              title: '投资计划成立日期',
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: this.state.deferDateData?.investPlanSetupDate ? this.state.deferDateData?.investPlanSetupDate : undefined,
              disabled: true,
            },
            {
              dataIndex: 'investPlanTerminateDate',
              title: '投资计划终止日期',
              disableBegin: this.state.deferDateData?.investPlanTerminateDate ? this.state.deferDateData?.investPlanTerminateDate : undefined,
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: this.state.deferDateData?.investPlanTerminateDate ? this.state.deferDateData?.investPlanTerminateDate : undefined,
              rules: [{ required: true, message: '请选择投资计划终止日期!' }],
            },
          ]}
          autoLayout={false}
          rowNumber={2}
          onRef={(ref) => {
            this.deferDateInfoRef = ref;
          }}
        />
      </>
    );
  };
  render() {
    const { columns, dataSource, total, currentPage, numInPage, operatePageVisible, operateType, operateId } = this.state;
    const {
      OutsourceInvestMsgMaintainM: { assetType },
    } = this.props;
    if (columns?.length && columns[columns?.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        width: 250,
        operates: [
          {
            title: '展期',
            onClick: (record, index) => {
              this.deferDate(record);
            },
            rules: {
              // 之前版本 --系统日期晚于或等于终止日期，才展示该按钮。(终止日期>系统日期，隐藏)
              //仅系统日期早于【投资计划终止日期】，才展示该按钮，【投资计划终止日期】无值时，也不提供展期功能
              hide: {
                relation: 'or',
                items: [
                  { key: 'investPlanTerminateDate', value: [moment()], relation: ['<'] },
                  { key: 'investPlanTerminateDate', value: [null], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '估值解析',
            onClick: (record, index) => {
              this.valuateItem(record);
            },
            rules: {
              // 委外投资属性 为 集合管理 时，隐藏估值解析
              hide: { items: [{ key: 'outsourceInvestProperty', value: ['集合管理'], relation: ['='] }] },
            },
          },
          {
            title: '详情',
            onClick: (record, index) => {
              this.itemDetail(record);
            },
          },
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editItem(record);
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteItem(record);
            },
          },
        ],
      });
    }
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'searchName',
          title: '代码或名称',
          type: DATA_ENTRY.INPUT,
          placeholder: '请输入代码或名称进行模糊搜索',
          allowClear: true,
          showSearch: true,
        },
        {
          dataIndex: 'assetType',
          title: '资产类别',
          type: DATA_ENTRY.SELECT,
          dataSource: assetType,
          allowClear: true,
        },
        {
          dataIndex: 'manager',
          title: '管理人',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
          showSearch: true,
        },
        {
          dataIndex: ['investPlanSetupDateStart', 'investPlanSetupDateEnd'],
          title: '成立日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => {
            this.startDateRef = ref;
          },
          disableFuture: false,
          self: this.startDateRef,
          allowClear: true,
        },
        {
          dataIndex: ['investPlanTerminateDateStart', 'investPlanTerminateDateEnd'],
          title: '终止日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => {
            this.endDateRef = ref;
          },
          disableFuture: false,
          self: this.endDateRef,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    const newColumns =
      columns?.map((x) => {
        if (x.key == 'investPlanSetupDate' || x.key == 'money' || x.key == 'investPlanTerminateDate' || x.key == 'secuabbr' || x.key == 'tradingCode') {
          return {
            ...x,
            width: '200px',
          };
        }
        if (x.key == 'fundUseIndustry') {
          return {
            ...x,
            width: '250px',
          };
        }
        if (x.key == 'outsourceInvestProperty' || x.key == 'outsourcedAssetNum') {
          return {
            ...x,
            width: '150px',
          };
        }
        if (x.key == 'assetType') {
          return {
            ...x,
            width: '120px',
          };
        }
        return x;
      }) || undefined;
    return (
      <ContentPackage
        title='委外投资维护'
        contentHtml={
          <div>
            <div style={{ display: operatePageVisible ? 'none' : 'block' }}>
              <div style={{ marginBottom: '10px' }}>
                <AdvancedSearch {...searchProps} />
              </div>
              <div>
                <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={this.addClick} />
              </div>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                current={currentPage}
                total={total}
                pageSize={numInPage}
                rowKey='id'
                selfScrollY={true}
                scroll={{ x: 'max-content' }}
                onChange={this.handleTableChange}
              />
            </div>
            {operatePageVisible ? (
              <div style={{ height: '100%' }}>
                <UpdateModelC
                  onBack={this.onBack}
                  onRef={(ref) => {
                    this.$operatePageC = ref;
                  }}
                  type={operateType} //操作类型,  1) 新增, 2) 编辑, 3) 详情, 4) 估值解析
                  operateId={operateId}
                />
              </div>
            ) : (
              ''
            )}
            <ModalC
              title={'展期'}
              visible={this.state.deferDateVisible}
              maskClosable={false}
              onOk={this.deferDateOk}
              destroyOnClose={true}
              confirmLoading={this.props.loading.effects['OutsourceInvestMsgMaintainM/deferDate'] == true}
              onCancel={this.deferDateCancel}
              width={900}
            >
              {this.deferDateInfo()}
            </ModalC>
          </div>
        }
      />
    );
  }
}
